package ezXpns.utils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;

/**
 * Utilities for DateTime manipulation
 */

//@author A0088827L
public class DateTimeUtils {
	public static Pair<Date, Date> getDayRange(Date date) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		setToMidnight(calendar);
		
		Date lowerBound = calendar.getTime();
		// next day
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MILLISECOND, -1);
		Date upperBound = calendar.getTime();

		return new ImmutablePair<Date, Date>(lowerBound, upperBound);
	}
	
	public static Pair<Date, Date> getMonthRange(Date date) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		setToMidnight(calendar);
		
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date lowerBound = calendar.getTime();
		//next month
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MILLISECOND, -1);
		Date upperBound = calendar.getTime();
		
		return new ImmutablePair<Date, Date>(lowerBound, upperBound);
	}
	
	public static Pair<Date, Date> getYearRange(Date date) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		setToMidnight(calendar);
		
		calendar.set(Calendar.DAY_OF_YEAR,1);
		Date lowerBound = calendar.getTime();
		//next year
		calendar.add(Calendar.YEAR, 1);
		calendar.set(Calendar.DAY_OF_YEAR, 1);
		calendar.add(Calendar.MILLISECOND, -1);
		Date upperBound = calendar.getTime();
		
		return new ImmutablePair<Date, Date>(lowerBound, upperBound);
	}
	
	public static Pair<Date, Date> getBeginningRange(Date date) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(new Date(0));
		setToMidnight(calendar);
		
		Date lowerBound = calendar.getTime();
		//next year
		
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		calendar.add(Calendar.MILLISECOND, -1);
		Date upperBound = calendar.getTime();
		
		return new ImmutablePair<Date, Date>(lowerBound, upperBound);
	}
	
	private static Calendar setToMidnight(Calendar calendar) {
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		return calendar;
	}
}
